﻿#include "stdafx.h"
#include "UserInit.h"
#include "MobileGameDlg.h"
#include "tlhelp32.h"

CIniFile g_IniFile;
CIniFile g_AccountFile;
CIniFile g_RoleNameFile;
CIniFile g_MoneyFile;
CIniFile g_TaskSpeedFile;
CIniFile g_ChangHaoStateFile;//成号状态
CStringArray arrAdsl;
CADSL adsl;

Cdmsoft *m_GlobalDM;//全局大漠
Cdmsoft *m_OnLineDM;
int m_GNum;
bool m_GState=true;
bool m_CheckState=false;
int m_GCount;
float m_fSim=0.90;//相似度
Cdmsoft *m_DM[20];
CLuck g_cLuck;
long m_GGameHwnd;
CString m_SimulatorPath;
CString g_Dnplayer2Path;
CString g_strDesktopPath;
map<CString, OcrDetail>ocrMap;
ScriptSetupInfo m_ScriptSet[20];
VARIANT intX, intY;


int SplitVARIANT(CString source, VARIANT* nlist, CString divKey) {

	int j = 0; int Number = 0; int m_pos, d_len = divKey.GetLength();
	while (TRUE)
	{
		m_pos = source.Find(divKey, j);
		if (m_pos == -1 && j == 0) { break; }
		if (m_pos == -1 && j != 0)
		{
			
			nlist[Number].lVal = _wtof(source.Mid(j, source.GetLength() - j));
			nlist[Number].lVal = nlist[Number].lVal < 0 ? 0 : nlist[Number].lVal;
			break;
		}
		if (j == 0)
		{
			nlist[Number].lVal = _wtof(source.Mid(0, m_pos));
			nlist[Number].lVal = nlist[Number].lVal < 0 ? 0 : nlist[Number].lVal;
		}
		else {
			nlist[Number].lVal = _wtof(source.Mid(j, m_pos - j));
			nlist[Number].lVal = nlist[Number].lVal < 0 ? 0 : nlist[Number].lVal;
		}
		j = m_pos + d_len;
		Number++;
	}
	return Number;
}


CString NumberToString(LONG Number)
{
	CString sTring;
	sTring.Format(_T("%ld"), Number);
	return sTring;
}

BOOL FolderExists(CString s)
{
	DWORD attr;
	attr = GetFileAttributes(s);
	return (attr != (DWORD)(-1)) &&
		(attr & FILE_ATTRIBUTE_DIRECTORY);
}
//创建一个目录
BOOL CreateDir(CString P)
{
	int len = P.GetLength();
	if (len < 2) return false;

	if ('\\' == P[len - 1])
	{
		P = P.Left(len - 1);
		len = P.GetLength();
	}
	if (len <= 0) return false;

	if (len <= 3)
	{
		if (FolderExists(P))return true;
		else return false;
	}

	if (FolderExists(P))return true;

	CString Parent;
	Parent = P.Left(P.ReverseFind('\\'));

	if (Parent.GetLength() <= 0)return false;

	BOOL Ret = CreateDir(Parent);

	if (Ret)
	{
		SECURITY_ATTRIBUTES sa;
		sa.nLength = sizeof(SECURITY_ATTRIBUTES);
		sa.lpSecurityDescriptor = NULL;
		sa.bInheritHandle = 0;
		Ret = (CreateDirectory(P, &sa) == TRUE);
		return Ret;
	}
	else
		return FALSE;
}

//分割字符串
void StringSplit(CString source, CStringArray& dest, char division)
{
	if (source.IsEmpty())
		return;
	dest.RemoveAll();
	for (int i = 0; i < source.GetLength(); i++)
	{
		if (source.GetAt(i) == division)
		{
			dest.Add(source.Left(i));
			source.Delete(0, i + 1);
			i = 0;
		}
	}
	dest.Add(source);
}



DWORD RandomNumber(DWORD dwNumber1, DWORD dwNumber2)
{
	DWORD dwTemp;
	__asm
	{
		push ecx
		push edx
		rdtsc
		mov ecx, 0x17
		mul ecx
		add eax, 0x7
		mov ecx, dwNumber2//ss:[ebp + 0c]
		sub ecx, dwNumber1//ss : [ebp + 8]
		inc ecx
		xor edx, edx
		div ecx
		add edx, dwNumber1//ss : [ebp + 8]
		mov dwTemp, edx
		pop edx
		pop ecx
	}
	return dwTemp;
}

DWORD WINAPI StartScript1()
{
	return 0;
}
DWORD WINAPI OnlinCheck(LPVOID lParam) {
	
	int ret = m_OnLineDM->BindWindowEx(m_GGameHwnd, L"gdi", L"normal", L"normal", L"", 0);
	while (m_GState)
	{
		if (m_OnLineDM->CmpColor(569, 717, L"fb6bd1", 0.9) == 0) {
			m_OnLineDM->KeyPress(35);
			DbgOut("补血中....");
		}
		m_OnLineDM->delay(500);
		long nMapHwnd = (long)m_OnLineDM->FindWindow(L"MapleStoryClass", L"MapleStory");
		if (nMapHwnd <= 0) {
			break;
		}
	}
	m_OnLineDM->UnBindWindow();
	return 0;
}


DWORD WINAPI StartScript(LPVOID lParam)
{
	ScriptSetupInfo* pSSI = (ScriptSetupInfo*)lParam;

	int iFreeDmIndex = pSSI->m_iDmIndex;
	int iIndex = pSSI->m_iControlIndex;

	//OpenSimulator(iFreeDmIndex);

	g_MobileGameDlg->InitUIGameInfo(iIndex, m_ScriptSet[iFreeDmIndex].m_GameInfoSt);//初始化一些信息


	g_MobileGameDlg->m_list_info.SetItemText(iIndex, 8, NumberToString(iFreeDmIndex));//模拟器序号

	long hHandle = NULL;
	CString strSimulatorTitleName;
	if (iFreeDmIndex == 0)
	{
		strSimulatorTitleName = L"雷电模拟器";
	}
	else
	{
		strSimulatorTitleName.Format(L"雷电模拟器-%d", iFreeDmIndex);
	}

	while (true)
	{
		hHandle = (long) ::FindWindow(NULL, strSimulatorTitleName);
		DbgOut(L"[sdn] hHandle:%d", hHandle);
		if ((int)hHandle)
		{
			break;
		}
		Sleep(3000);
	}

	//排序窗口
	DbgOut(L"[sdn] hHandle:%d", hHandle);
	//if (g_pPage1->m_radio_tran_expan.GetCheck())
	//{
	//	g_pPage1->OnBnClickedBtnHengxiang();
	//}
	//else
	//{
	//	g_pPage1->OnBnClickedBtnZhongxiang();
	//}


	g_pPage1->OnBnClickedBtnHengxiang();

	BOOL bRet = RegisterDM(iFreeDmIndex);
	if (!bRet)
	{
		AfxMessageBox(L"注册单个大漠失败");
		return 0;
	}

	g_MobileGameDlg->m_list_info.SetItemText(iIndex, 10, L"运行中");
	m_DM[iFreeDmIndex]->SetWindowState((long)hHandle, 1);

	//long hGameHandle = GetSubWindow(hHandle);
	long hGameHandle = m_DM[iFreeDmIndex]->GetWindow(hHandle, 1);
	DbgOut(L"[sdn] 子窗口句柄:%d", hGameHandle);
	while (true)
	{
		Sleep(3000);
		hGameHandle = m_DM[iFreeDmIndex]->GetWindow(hHandle, 1);
		if (hGameHandle != 0)
		{
			break;
		}
		DbgOut(L"[sdn] ---子窗口句柄:%d", hGameHandle);
	}

	//m_ScriptSet[iFreeDmIndex].m_iDmIndex = iFreeDmIndex;//大漠序号
	//m_ScriptSet[iFreeDmIndex].m_iControlIndex = iIndex;//控制台序号
	m_ScriptSet[iFreeDmIndex].m_hGameHandle = hGameHandle;
	//m_ScriptSet[iFreeDmIndex].m_hControlHandle = (long)g_MobileGameDlg->m_hWnd;//用于发送消息
	DbgOut(L"[sdn] 绑定 le");

	g_MobileGameDlg->m_list_info.SetItemText(iIndex, 1, NumberToString(hGameHandle));

	//m_DM[iFreeDmIndex]->SetWindowState((long)hGameHandle, 1);

	long dm_ret = m_DM[iFreeDmIndex]->BindWindowEx((long)hGameHandle,
		L"gdi", L"windows3", L"windows",
		NULL,
		0);

	/*	long dm_ret = m_DM[iFreeDmIndex]->BindWindowEx((long)hGameHandle,
	"gdi",
	"windows",
	"windows",
	NULL,
	0);*/
	//long dm_ret = aDm[nID]->BindWindowEx(lHwnd,
	//	"dx.graphic.opengl",
	//	"dx.mouse.position.lock.api|dx.mouse.clip.lock.api|dx.mouse.input.lock.api|dx.mouse.state.api|dx.mouse.api|dx.mouse.cursor",
	//	"dx.keypad.input.lock.api|dx.keypad.state.api|dx.keypad.api",
	//	NULL,
	//long dm_ret = m_DM[iFreeDmIndex]->BindWindowEx((long)hGameHandle, "dx.graphic.opengl", "windows", "windows", "dx.public.down.cpu", 0);
	Sleep(2000);
	if (dm_ret <= 0)
	{
		AfxMessageBox(L"游戏绑定失败!");
		ClearOneDM(iFreeDmIndex);
		return 0;
	}

	int iRate = g_IniFile.GetInt(_T("Set"), _T("CPU"));
	if (iRate == 0)
	{
		iRate = 20;
	}
	//DownCpu(iFreeDmIndex, iRate);
	Sleep(5000);

	CString strRoleNum = g_IniFile.GetString(L"Set", L"账号角色");//2
	int iRoleNum = 1;
	if (iRoleNum == 0)
	{
		iRoleNum = 1;
	}
	while (true)
	{
		if (m_ScriptSet[iFreeDmIndex].m_GameInfoSt.m_iRoleIndex > iRoleNum)
		{
			DbgOut(L"[sdn] Here break1");
			m_ScriptSet[iFreeDmIndex].m_GameInfoSt.m_iRoleIndex = 1;
			break;
		}
		DbgOut(L"[sdn] 处理当前任务开始xxxxxxxxxxxxxxxxxxxx");
		DealCurTaskProcess(iFreeDmIndex);

		if (ChangeRole(iFreeDmIndex) != 1)
		{
			//开始下一个角色

		}
		Sleep(3000);
	}
	DbgOut(L"[sdn] 设置界面完成");
	//设置界面完成
	m_ScriptSet[iFreeDmIndex].m_GameInfoSt.m_strRunState = L"完成";
	ShowConsoleInfo(iFreeDmIndex, 10);
	//设置配置文件完成
	CString strSet;
	strSet.Format(L"%d", m_ScriptSet[iFreeDmIndex].m_iControlIndex + 1);
	g_AccountFile.SetInt(strSet, L"完成", 1);
	//Account.ini
	/*DbgOut("[sdn] ---------------开始下一个账号----------------");
	::SendMessage((HWND)m_ScriptSet[iFreeDmIndex].m_hControlHandle, WM_USERMONITOR, 2, (LPARAM)iFreeDmIndex);
	for (int N = 0; N<30; N++)
	{
	Sleep(2000);
	}*/

	return 0;
}

void KillProcess(CString sExeName)
{
	HANDLE hSnapShot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hSnapShot == 0)
		return;
	PROCESSENTRY32 thePE;
	thePE.dwSize = sizeof(PROCESSENTRY32);


	//遍历正在运行的第一个系统进程


	bool Status = Process32First(hSnapShot, &thePE);
	bool bHaveFlag = false;
	DWORD ProcessID = 0;


	while (Status)
	{
		//遍历正在运行的下一个系统进程  
		Status = Process32Next(hSnapShot, &thePE);
		//找到相应的进程 **.exe


		// if(0 == wcscmp(thePE.szExeFile,L""))
		CString sFindName = thePE.szExeFile;
		CString sTemp = sExeName.Mid(0, sFindName.GetLength());


		if (sFindName == sTemp)
		{
			bHaveFlag = true;
			ProcessID = thePE.th32ProcessID;


			////结束指定的进程 ProcessID
			if (!TerminateProcess(OpenProcess(PROCESS_TERMINATE || PROCESS_QUERY_INFORMATION, false, ProcessID), 0))
			{
				//AfxMessageBox(L"无法终止指定的进程！", MB_ICONWARNING || MB_OK);
			}
			else
			{
				//AfxMessageBox(L"进程结束！", MB_ICONWARNING || MB_OK);
				break;
			}
		}
	}
	CloseHandle(hSnapShot);
}

bool runScript(CString str) {
	bool(*pn[])(OcrDetail) = { CmpCol,FindCol,FindMulCol,FindPic,FindStr };
	OcrDetail ocrDetail = ocrMap[str];
	int nAction = _wtoi(ocrDetail.sAction);
	return pn[nAction](ocrDetail);
}

bool FindCol(OcrDetail ocrDetail) {
	VARIANT nPoint[4];
	SplitVARIANT(ocrDetail.sPoint, nPoint, L",");
	m_GlobalDM->FindColor(nPoint[0].lVal, nPoint[1].lVal, nPoint[2].lVal, nPoint[3].lVal, ocrDetail.sOcrText, 0.9, 0, &intX, &intY);
	if (intX.lVal == -1) {
		return false;
	}
	else {
		return ocrType(ocrDetail);
	}
}

bool FindMulCol(OcrDetail ocrDetail) {

	VARIANT nPoint[4];
	SplitVARIANT(ocrDetail.sPoint, nPoint, L",");

	CString str;
	str = ocrDetail.sOcrText;
	int nIndex = str.Find(L",");
	str = str.Mid(0, nIndex);
	m_GlobalDM->FindMultiColor(nPoint[0].lVal, nPoint[1].lVal, nPoint[2].lVal, nPoint[3].lVal, str, ocrDetail.sOcrText, 0.9, 0, &intX, &intY);
	if (intX.lVal == -1) {
		return false;
	}
	else {
		return ocrType(ocrDetail);
	}
}

bool CmpCol(OcrDetail ocrDetail) {

	CStringArray arrStr;
	StringSplit(ocrDetail.sOcrText, arrStr, '|');
	BOOL bl = false;
	for (int i = 0; i < arrStr.GetCount(); i++)
	{
		CStringArray arrStr1;
		StringSplit(arrStr[i], arrStr1,',');
		CString str1 = arrStr1[0];
		CString str2 = arrStr1[1];
		CString str3 = arrStr1[2];
		if (m_GlobalDM->CmpColor(_wtof(arrStr1[0]), _wtof(arrStr1[1]), arrStr1[2], 0.95) == 1) { //未匹配
			bl = true;
		}
		else {
			if (i == 0) {

				intX.lVal = _wtol(arrStr1[0]);
				intY.lVal = _wtol(arrStr1[1]);
			}

		}
	}
	if (bl) {
		return false;
	}
	else {
		return ocrType(ocrDetail);
	}
}

bool FindPic(OcrDetail ocrDetail) {
	VARIANT nPoint[4];
	CString str = ocrDetail.sPoint;
	SplitVARIANT(str, nPoint, L",");
	//CString str;
	str.Format(L"%s%s", ocrDetail.sName, L".bmp");
	VARIANT m_picData, m_picSize;
	if (ocrDetail.nCount > 0) {
		for (int i = 0; i < ocrDetail.nCount; i++)
		{
			m_GlobalDM->FindPic(nPoint[0].lVal - 10, nPoint[1].lVal - 10, nPoint[2].lVal + 10, nPoint[3].lVal + 10, str, L"202020", 0.90, 0, &intX, &intY);
			if (intX.lVal == -1)
				return false;
			else {
				return ocrType(ocrDetail);
			}
		}
	}
	else {
		m_GlobalDM->FindPic(nPoint[0].lVal - 10, nPoint[1].lVal - 10, nPoint[2].lVal + 10, nPoint[3].lVal + 10, str, L"202020", 0.90, 0, &intX, &intY);
		if (intX.lVal == -1)
			return false;
		else {
			return ocrType(ocrDetail);
		}
	}


}

bool FindStr(OcrDetail ocrDetail) {
	VARIANT nPoint[4];
	SplitVARIANT(ocrDetail.sPoint, nPoint, L",");
	m_GlobalDM->FindStrFast(nPoint[0].lVal - 3, nPoint[1].lVal - 3, nPoint[2].lVal + 3, nPoint[3].lVal + 3, ocrDetail.sName, ocrDetail.sOcrText, 0.9, &intX, &intY);
	if (intX.lVal == -1)
		return false;
	else {
		return ocrType(ocrDetail);
	}
}
bool(*funOcrType[])(OcrDetail) = { dmClick,dmDoubleClick,dmSlide, dmDoubleClick };

bool ocrType(OcrDetail ocrDetail) {
	CString str;
	int nType = _wtoi(ocrDetail.sType);
	if (nType == 0) {
		if (intX.lVal > 0)
			return true;
		else
			return false;
	}
	nType--;
	funOcrType[nType](ocrDetail);
	return Continued(ocrDetail);
}
bool dmClick(OcrDetail ocrDetail) {
	VARIANT nOffset[2] = { 0,0 };
	SplitVARIANT(ocrDetail.sOffset, nOffset, L",");
	m_GlobalDM->MoveToEx(intX.lVal + nOffset[0].lVal, intY.lVal + nOffset[1].lVal, 5, 5);
	m_GlobalDM->LeftClick();
	m_GlobalDM->delay(150);
	return true;
}
bool dmDoubleClick(OcrDetail ocrDetail) {
	//g_pDmLD->MoveToEx(ocrInfo.OffsetX, ocrInfo.OffsetY, 5, 5);
	m_GlobalDM->delay(100);
	m_GlobalDM->LeftClick();
	m_GlobalDM->delay(150);
	m_GlobalDM->LeftClick();
	return true;
}
bool dmSlide(OcrDetail ocrDetail) {
	return true;
}
bool dmContinued(OcrDetail ocrDetail) {
	return true;
}
bool ContinuedAction(int type, CString str) {

	int nSize;
	if (type == 1) {
		long x, y;
		x = _wtol(str.Tokenize(L",", nSize));
		y = _wtol(str.Tokenize(L",", nSize));
		m_GlobalDM->Click(x, y);
	}
	else if (type == 2) {

	}
	else if (type == 3)
	{
		long m_SimHwnd = m_GlobalDM->FindWindow(L"LDPlayerMainFrame", L"雷电模拟器");
		m_SimHwnd = m_GlobalDM->GetWindow(m_SimHwnd, 1);
		m_GlobalDM->SendString2(m_SimHwnd, str);
	}
	return true;
}

//分割数据处理 1:移动点击,2:滑动处理,3:字符串输入
bool Continued(OcrDetail ocrDetail) {
	//格式 1:x,y|x,y@2:abc@3
	int m2;
	CString m3;
	int nStart1 = 0;

	if (ocrDetail.sEnlarge != L"") {
		int istart = 0;
		if (ocrDetail.sEnlarge.Find(L"@") > 0) {
			while (istart == -1) {//分割 @符号
				CString m;
				m = ocrDetail.sEnlarge.Tokenize(L"@", istart);//1:1,2,3|1,2,3@2:1,2|1,2@3:1,2|3,3
				if (m != "" || m.GetLength() > 0) {
					int nStart = 0;
					while (nStart == -1)//分割 |符号
					{
						CString m1;
						m1 = m.Tokenize(L"|", nStart); //1:1, 2, 3 | 1, 2, 3
						if (m1 != L"" || m1.GetLength() > 0) {
							//第1组数据
							m2 = _wtoi(m1.Tokenize(L":", nStart1));
							m3 = m1.Tokenize(L":", nStart1);
							ContinuedAction(m2, m3);
						}
					}
				}
			}
		}
		else {
			m2 = _wtoi(ocrDetail.sEnlarge.Tokenize(L":", nStart1));
			m3 = ocrDetail.sEnlarge.Tokenize(L":", nStart1);
			ContinuedAction(m2, m3);
		}

	}
	m_GlobalDM->delay(1500);
	return true;
}


bool runScriptList(CString str) {
	int istart = 0;
	while (istart != -1) {//分割 @符号
		CString m;
		m = str.Tokenize(L"|", istart);
		runScript(m);
		Sleep(500);
	}
	return true;
}
bool CheckIPAddr() {
	CString str; //获取系统时间 　　

	CTime tm; tm = CTime::GetCurrentTime();

	str = tm.Format("%Y%m%d");
	CString dt;
	dt.Format(L"http://only-997227-218-13-34-109.nstool.netease.com/%s", str);
	//dt.Format(L"http://ip138.com", str);
	DeleteUrlCacheEntry(dt); // 清理缓存
	HRESULT hr = URLDownloadToFileA(0, CString2char(dt), "ipFile.txt", 0, NULL);
	if (hr != S_OK) {
		return L"";
	}

	CFile file;
	file.Open(_T("ipFile.txt"), CFile::modeRead);
	if (!file)
	{
		return L"";
	}
	ULONGLONG len = file.GetLength();
	char* buf = new char[len + 1];
	ZeroMemory(buf, len + 1);
	file.Read(buf, len);
	buf[len] = 0;
	CString ans = CString(buf);
	CString ip = L"";
	if (ans.Find(L"龙岩") > 1) {
		return true;
	}
	else {
		return false;
	}

}
CString GetNetIp()
{


	//两个查询网站供用户切换
//#if(1)
//	CString checkWeb = L"http://only-997227-218-13-34-109.nstool.netease.com/";
//	CString tagStr = L"您的IP地址信息: ";
//	CString endChar = L" ";
//#else
//	CString checkWeb = "http://www.ip138.com/ips1388.asp";
//	CString tagStr = "您的IP地址是：[";
//	CString endChar = "]";
//#endif
//
	//http://ip.dnsexit.com
	DeleteFile(L"ipFile.txt");
	CString tagStr = L"您的IP地址信息: ";
	CString endChar = L" ";
	CString str; //获取系统时间 　　

	CTime tm; tm = CTime::GetCurrentTime();

	str = tm.Format("%Y%m%d");
	CString dt;
	dt.Format(L"http://only-997227-218-13-34-109.nstool.netease.com/%s", str);
	//dt.Format(L"http://ip138.com", str);
	DeleteUrlCacheEntry(dt); // 清理缓存
	HRESULT hr = URLDownloadToFileA(0, CString2char(dt), "ipFile.txt", 0, NULL);
	if (hr != S_OK) {
		return L"";
	}

	CFile file;
	file.Open(_T("ipFile.txt"), CFile::modeRead);
	if (!file)
	{
		return L"";
	}
	ULONGLONG len = file.GetLength();
	char* buf = new char[len + 1];
	ZeroMemory(buf, len + 1);
	file.Read(buf, len);
	buf[len] = 0;
	CString ans =CString( buf);
	CString ip = L"";

	int ix = ans.Find(tagStr);
	int endn = -1;
	if (ix>-1)
	{
		len = tagStr.GetLength();
		endn = ans.Find(endChar, ix + len);
		if (endn>-1)
		{
			ip = ans.Mid(ix + len, endn - ix - len);
		}
	}
	delete buf;
	file.Close();
	return ip;

}

//
//
//CInternetSession    session(_T("cctry.com"));
//CHttpFile           *pFile = NULL;
//CStdioFile          *ptFile = NULL;
//CString             strTemp = _T("");
//DWORD               dwStat = 0;
//
//try
//{
//	pFile = (CHttpFile *)session.OpenURL(_T("http://ip.dnsexit.com"));
//	pFile->QueryInfoStatusCode(dwStat);
//	if (dwStat == HTTP_STATUS_OK)
//	{
//		ptFile = (CStdioFile *)pFile;
//
//		ptFile->ReadString(strTemp);
//
//		pFile->Close();
//		session.Close();
//		return 0;
//	}
//}
//catch (CException* e)
//{
//	return strTemp;
//}
//
//return strTemp;

//bool CallCMD(CString cmd, CString &outPut, CString& errInfo)
//{
//	outPut = L"";
//	SECURITY_ATTRIBUTES sa;
//	HANDLE hRead, hWrite;
//	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
//	sa.lpSecurityDescriptor = NULL; //使用系统默认的安全描述符  
//	sa.bInheritHandle = TRUE; //创建的进程继承句柄  
//	if (!CreatePipe(&hRead, &hWrite, &sa, 0)) //创建匿名管道  
//	{
//		errInfo.Format("创建管道失败，错误码:%d", GetLastError());
//		//TRACE("创建管道失败，错误码:%d\n", GetLastError());
//		DbgOut("[sdn] %s", errInfo);
//		return false;
//	}
//
//	STARTUPINFO si;
//	PROCESS_INFORMATION pi;
//
//	ZeroMemory(&si, sizeof(STARTUPINFO));
//
//	si.cb = sizeof(STARTUPINFO);
//	GetStartupInfo(&si);
//	si.hStdError = hWrite;
//	si.hStdOutput = hWrite; //新创建进程的标准输出连在写管道一端  
//	si.wShowWindow = SW_HIDE; //隐藏窗口  
//	si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
//
//	TCHAR cmd2[1024];
//	_tcscpy_s(cmd2, cmd);
//	if (!CreateProcess(NULL, cmd2, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi)) //创建子进程  
//	{
//		errInfo.Format("创建CreateProcess失败，错误码:%d", GetLastError());
//		//errInfo = "创建CreateProcess失败，错误码:" + GetLastError();
//		DbgOut("[sdn] %s", errInfo);
//		return false;
//	}
//	CloseHandle(hWrite); //关闭管道句柄  
//
//	char buffer[81920] = { 0 };
//	DWORD bytesRead;
//
//	while (true)
//	{
//		if (ReadFile(hRead, buffer, 1, &bytesRead, NULL) == NULL) //读取管道  
//			break;
//		outPut += buffer;
//		//Sleep(100);
//	}
//	CloseHandle(hRead);
//	return true;
//}

//执行CMD命令返回命令结果
BOOL GetCmdResult(const TCHAR * szDosCmd, CString &sRetVal)
{
	CString errInfo;
	//创建管道
	SECURITY_ATTRIBUTES sa;
	HANDLE hRead, hWrite;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;
	if (!CreatePipe(&hRead, &hWrite, &sa, 0))
	{
		errInfo.Format(L"创建CreateProcess失败，错误码:%d", GetLastError());
		//errInfo = "创建CreateProcess失败，错误码:" + GetLastError();
		DbgOut("[sdn] %s", errInfo);
		return FALSE;
	}

	//组装命令行,长达1K的命令行,应该够用
	TCHAR command[1024];

	_tcscpy_s(command, L"Cmd.exe /C ");
	_tcscpy_s(command, szDosCmd);

	//返回进程在启动时被指定的STARTUPINFO结构
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	si.cb = sizeof(STARTUPINFO);
	GetStartupInfo(&si);
	si.hStdError = hWrite;            //把创建进程的标准错误重定向到管道输入  
	si.hStdOutput = hWrite;           //把创建进程的标准输出重定向到管道输入  
	si.wShowWindow = SW_HIDE;
	si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;

	//执行命名,创建子进程 
	//第五个参数bInHeritHandles也是一定要设置为TRUE,因为既然要让新进程能输出信息到调用他的进程里,就必须让新的进程继承调用进程的句柄.
	if (!CreateProcess(NULL, command, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))
	{
		errInfo.Format(L"创建CreateProcess失败，错误码:%d", GetLastError());
		//errInfo = "创建CreateProcess失败，错误码:" + GetLastError();
		DbgOut(L"[sdn] %s", errInfo);
		CloseHandle(hWrite);
		CloseHandle(hRead);
		return FALSE;
	}

	//关闭管道输入
	CloseHandle(hWrite);

	//读取管道输出
	DWORD dwRead = 0;
	DWORD dwBlock = 4096;
	char szBuffer[4096 + 1] = { 0 };
	char buffer[4096] = { 0 };
	DWORD bytesRead;
	CString str;
	while (ReadFile(hRead, buffer, 4095, &bytesRead, NULL))
	{
		DbgOut("[sdn] szBuffer:%s", buffer);
		//str.Format(L"%s\0", buffer);
		sRetVal += buffer;
	}

	//关闭管道输出
	CloseHandle(hRead);
	return TRUE;
}

/*
***********************************************************************
* 函数： TransCStringToTCHAR
* 描述：将CString 转换为 TCHAR*
* 日期：
***********************************************************************
*/
TCHAR* CString2TCHAR(CString &str)
{
	int iLen = str.GetLength();
	TCHAR* szRs = new TCHAR[iLen];
	lstrcpy(szRs, str.GetBuffer(iLen));
	str.ReleaseBuffer();
	return szRs;
}

/*
***********************************************************************
* 函数： TCHAR2Char
* 描述：将TCHAR* 转换为 char*
* 日期：



***********************************************************************
*/
char* TCHAR2char(TCHAR* tchStr)
{
	int iLen = 2 * wcslen(tchStr);//CString,TCHAR汉字算一个字符，因此不用普通计算长度 
	char* chRtn = new char[iLen + 1];
		wcstombs(chRtn, tchStr, iLen + 1);//转换成功返回为非负值 
	return chRtn;
}

/*

***********************************************************************
* 函数： char2tchar
* 描述：将 char* 转换为 TCHAR*
* 日期：


***********************************************************************
*/
TCHAR *char2tchar(char *str)
{
	int iLen = strlen(str);
	TCHAR *chRtn = new TCHAR[iLen + 1];
	mbstowcs(chRtn, str, iLen + 1);
	return chRtn;
}


/*

***********************************************************************
* 函数： CString2char
* 描述：将CString转换为 char*
* 日期：
***********************************************************************
*/
char* CString2char(CString &str)
{
	int len = str.GetLength();
	char* chRtn = (char*)malloc((len * 2 + 1) * sizeof(char));//CString的长度中汉字算一个长度 
	memset(chRtn, 0, 2 * len + 1);
	USES_CONVERSION;
	strcpy((LPSTR)chRtn, OLE2A(str.LockBuffer()));
	return chRtn;
}

/*
***********************************************************************
* 函 数 名：GetAnsiString
* 描 述：将CString（unicode）转换为char*(ANSI)
* 参 数：CString &s 要转换的CString
* 返 回 值：返回转换结果
* 创建日期：

* 最后修改：
***********************************************************************
*/
char* GetAnsiString(const CString &s)
{
	int nSize = 2 * s.GetLength();
	char *pAnsiString = new char[nSize + 1];
	wcstombs(pAnsiString, s, nSize + 1);
	return pAnsiString;
}

wstring AnsiToUnicodes(const string& str)
{
	int len = 0;
	len = str.length();
	int unicodeLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
	wchar_t * pUnicode;
	pUnicode = new wchar_t[unicodeLen + 1];
	memset(pUnicode, 0, (unicodeLen + 1) * sizeof(wchar_t));
	::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, (LPWSTR)pUnicode, unicodeLen);
	wstring rt;
	rt = (wchar_t*)pUnicode;
	delete pUnicode;
	return rt;
}
//wstring UTF8ToUnicode(const string& str)
//{
//	int len = 0;
//	len = str.length();
//	int unicodeLen = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
//	wchar_t * pUnicode;
//	pUnicode = new wchar_t[unicodeLen + 1];
//	memset(pUnicode, 0, (unicodeLen + 1) * sizeof(wchar_t));
//	::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, (LPWSTR)pUnicode, unicodeLen);
//	wstring rt;
//	rt = (wchar_t*)pUnicode;
//	delete pUnicode;
//	return rt;
//}

CString GetIp()

{
//
//
//	CString csSource;
//	CString csAddress;
//	CString csIPAddress;
//	csIPAddress.Format(_T(" "));
//	CInternetSession mySession(NULL, 0);
//	CHttpFile* myHttpFile = NULL;
//	csAddress = _T("http://ip.dnsexit.com/");//ip138网页 http://www.ip138.com/ip2city.asp
//	myHttpFile = (CHttpFile*)mySession.OpenURL(csAddress);//读取网络地址
//	while (myHttpFile->ReadString(csSource))
//	{  //循环读取下载来的网页文本
//	   //code 转换
//		//ReadStringCharToUnicode(csSource);
//		char *pStr = (char*)csSource.GetBuffer(csSource.GetLength()); //取得str对象的原始字符串
//		int nBufferSize = MultiByteToWideChar(CP_UTF8, 0, pStr, -1, NULL, 0); //取得所需缓存的多少
//		wchar_t *pBuffer = (wchar_t*)malloc(nBufferSize * sizeof(wchar_t));//申请缓存空间
//		MultiByteToWideChar(CP_UTF8, 0, pStr, -1, pBuffer, nBufferSize * sizeof(wchar_t));//转码
//																						  //MessageBox(pBuffer); //显示
//		csIPAddress.Format(_T("%s"), pBuffer);
//
//	}
//	return csIPAddress;
//}
//
//void ReadStringCharToUnicode(CString &str)
//{
//	char *szBuf = new char[str.GetLength() + 2];//注意“+1”，char字符要求结束符，而CString没有
//	memset(szBuf, '\0', str.GetLength());
//
//	int i;
//	for (i = 0; i < str.GetLength(); i++)
//	{
//		szBuf[i] = (char)str.GetAt(i);
//	}
//	szBuf[i] = '\0';//结束符。否则会在末尾产生乱码。
//
//	int nLen;
//	WCHAR *ptch;
//	CString strOut;
//	if (szBuf == NULL)
//	{
//		return;
//	}
//	nLen = MultiByteToWideChar(CP_ACP, 0, szBuf, -1, NULL, 0);//获得需要的宽字符字节数
//	ptch = new WCHAR[nLen];
//	memset(ptch, '\0', nLen);
//	MultiByteToWideChar(CP_ACP, 0, szBuf, -1, ptch, nLen);
//	str.Format(_T("%s"), ptch);
//
//	if (NULL != ptch)
//		delete[] ptch;
//	ptch = NULL;
//
//	if (NULL != szBuf)
//		delete[]szBuf;
//	szBuf = NULL;
//	return;


//两个查询网站供用户切换
//#if(1)
//	CString checkWeb = L"http://only-997227-218-13-34-109.nstool.netease.com/";
//	CString tagStr = L"您的IP地址信息: ";
//	CString endChar = L" ";
//#else
//	CString checkWeb = "http://www.ip138.com/ips1388.asp";
//	CString tagStr = "您的IP地址是：[";
//	CString endChar = "]";
//#endif
//
//
//	HRESULT hr = URLDownloadToFileW(0, checkWeb, _T("ipFile.txt"), 0, NULL);
//	if (hr != S_OK) {
//		return L"";
//	}
//
//	CFile file;
//	file.Open(_T("ipFile.txt"), CFile::modeRead);
//	if (!file)
//	{
//		return L"";
//	}
//	ULONGLONG len = file.GetLength();
//	char* buf = new char[len + 1];
//	ZeroMemory(buf, len + 1);
//	file.Read(buf, len);
//	buf[len] = 0;
//	CString ans = buf;
//	CString ip = L"";
//
//	int ix = ans.Find(tagStr);
//	int endn = -1;
//	if (ix>-1)
//	{
//		len = tagStr.GetLength();
//		endn = ans.Find(endChar, ix + len);
//		if (endn>-1)
//		{
//			ip = ans.Mid(ix + len, endn - ix - len);
//		}
//	}
//	delete buf;
//	file.Close();
//	return ip;
return L"";
}